<template>
  <div class="cart-list-container">
    <div class="page-header">
      <h2>购物车管理</h2>
      <div class="header-actions">
        <el-input
          v-model="searchQuery"
          placeholder="搜索用户名/商品名称"
          clearable
          @clear="handleSearch"
          style="width: 250px;"
        >
          <template #append>
            <el-button @click="handleSearch">
              <el-icon><Search /></el-icon>
            </el-button>
          </template>
        </el-input>
        <el-button type="primary" @click="refreshData">
          <el-icon><RefreshRight /></el-icon> 刷新
        </el-button>
      </div>
    </div>

    <!-- 购物车列表统计 -->
    <el-card shadow="hover" class="stats-card" v-if="userCartGroups.length > 0">
      <div class="stats-info">
        <div class="stats-item">
          <span class="stats-label">总用户数：</span>
          <span class="stats-value">{{ userCartGroups.length }}</span>
        </div>
        <div class="stats-item">
          <span class="stats-label">总商品数：</span>
          <span class="stats-value">{{ getTotalCartItems() }}</span>
        </div>
        <div class="stats-item">
          <span class="stats-label">总商品金额：</span>
          <span class="stats-value price">¥{{ getTotalAmount() }}</span>
        </div>
      </div>
    </el-card>

    <el-card shadow="never" class="table-card">
      <el-table
        v-loading="loading"
        :data="userCartGroups"
        border
        style="width: 100%"
        row-key="userId"
        class="cart-table"
      >
        <el-table-column type="expand">
          <template #default="props">
            <div class="cart-items-container">
              <el-table
                :data="props.row.cartItems"
                border
                style="width: 100%"
                :show-header="true"
                class="cart-items-table"
              >
                <el-table-column label="商品图片" width="80" align="center">
                  <template #default="scope">
                    <el-image
                      :src="getProductImage(scope.row)"
                      fit="cover"
                      :preview-src-list="[getProductImage(scope.row)]"
                      class="product-image-small"
                    />
                  </template>
                </el-table-column>
                <el-table-column prop="id" label="商品ID" width="180" />
                <el-table-column label="商品信息" min-width="300">
                  <template #default="scope">
                    <div class="product-info">
                      <div class="product-details">
                        <div class="product-title">{{ getProductTitle(scope.row) }}</div>
                        <div class="product-specs" v-if="getProductSpecs(scope.row)">
                          <el-tag v-for="(val, key) in getProductSpecs(scope.row)" 
                                  :key="key" 
                                  size="small" 
                                  type="info" 
                                  effect="plain"
                                  class="spec-tag">
                            {{ key }}: {{ val }}
                          </el-tag>
                        </div>
                        <div class="product-shop" v-if="scope.row.spuVO && scope.row.spuVO.shopId">
                          <el-tag size="small" type="success">店铺ID: {{ scope.row.spuVO.shopId }}</el-tag>
                        </div>
                      </div>
                    </div>
                  </template>
                </el-table-column>
                <el-table-column label="单价" width="120" align="center">
                  <template #default="scope">
                    <span class="price">¥{{ getProductPrice(scope.row) }}</span>
                  </template>
                </el-table-column>
                <el-table-column label="数量" width="80" align="center">
                  <template #default="scope">
                    {{ scope.row.quantity || scope.row.number || 1 }}
                  </template>
                </el-table-column>
                <el-table-column label="小计" width="120" align="center">
                  <template #default="scope">
                    <span class="price">¥{{ getSubtotal(scope.row).toFixed(2) }}</span>
                  </template>
                </el-table-column>
                <el-table-column label="状态" width="100" align="center">
                  <template #default="scope">
                    <el-tag :type="scope.row.selected ? 'success' : 'info'">
                      {{ scope.row.selected ? '已选中' : '未选中' }}
                    </el-tag>
                  </template>
                </el-table-column>
                <el-table-column label="操作" width="120" align="center">
                  <template #default="scope">
                    <el-button 
                      type="danger" 
                      size="small" 
                      @click="handleDelete(scope.row)"
                      :loading="deleteLoading === scope.row.id"
                    >
                      删除
                    </el-button>
                  </template>
                </el-table-column>
              </el-table>
            </div>
          </template>
        </el-table-column>
        
        <el-table-column prop="userId" label="用户ID" width="100" align="center" />
        <el-table-column prop="userName" label="用户名" width="150" />
        <el-table-column label="购物车商品" width="150" align="center">
          <template #default="scope">
            <div class="cart-count">
              <el-badge :value="scope.row.cartItems.length" type="primary">
                <span>商品数量</span>
              </el-badge>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="总金额" width="150" align="center">
          <template #default="scope">
            <span class="price">¥{{ getUserCartTotal(scope.row).toFixed(2) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" min-width="200" align="center">
          <template #default="scope">
            <el-button 
              type="primary" 
              size="small" 
              @click="expandRow(scope.row)"
            >
              查看详情
            </el-button>
            <el-button 
              type="danger" 
              size="small" 
              @click="handleClearUserCart(scope.row.userId, scope.row.userName)"
            >
              清空购物车
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, onMounted, reactive, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search, Delete, RefreshRight } from '@element-plus/icons-vue'
import { getCartList, deleteCartItem, clearUserCart } from '@/api/admin-cart'

// 数据加载状态
const loading = ref(false)
const deleteLoading = ref(null)

// 分页相关
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)

// 搜索相关
const searchQuery = ref('')

// 购物车列表数据
const cartList = ref([])
// 用户购物车分组数据
const userCartGroups = ref([])

// 展开行的引用
const tableRef = ref(null)
const expandRow = (row) => {
  // 这里可以实现点击按钮展开行的逻辑
  // 由于Element Plus的表格没有直接提供通过代码展开行的API
  // 我们可以通过点击事件模拟用户点击展开图标
  const index = userCartGroups.value.findIndex(item => item.userId === row.userId)
  if (index !== -1) {
    // 这里只是一个提示，实际上无法直接控制展开
    ElMessage.info('请点击行前的展开图标查看详情')
  }
}

// 获取购物车列表数据
const fetchCartList = async () => {
  loading.value = true
  try {
    const params = {
      page: currentPage.value,
      size: pageSize.value,
      query: searchQuery.value
    }
    
    // 使用API服务获取数据
    const response = await getCartList(params)
    console.log('API原始响应:', response)
    
    // 处理返回的数据格式
    let processedData = []
    
    // 根据响应拦截器，response已经是res.data了，不需要再取.data
    if (response && Array.isArray(response)) {
      // 处理嵌套结构：用户列表包含购物车列表
      response.forEach(user => {
        if (user.cartListDTOs && Array.isArray(user.cartListDTOs)) {
          // 为每个购物车项添加用户信息
          const cartItems = user.cartListDTOs.map(item => ({
            ...item,
            userName: user.username || user.nickName,
            // 确保用户ID存在
            userId: item.userId || user.id
          }))
          processedData = [...processedData, ...cartItems]
        }
      })
    } else if (response && response.records) {
      // 分页对象
      processedData = response.records
      total.value = response.total || 0
    } else if (response && response.success && response.data) {
      // 处理 { success: true, code: 200, data: [...] } 格式
      if (Array.isArray(response.data)) {
        response.data.forEach(user => {
          if (user.cartListDTOs && Array.isArray(user.cartListDTOs)) {
            const cartItems = user.cartListDTOs.map(item => ({
              ...item,
              userName: user.username || user.nickName,
              userId: item.userId || user.id
            }))
            processedData = [...processedData, ...cartItems]
          }
        })
      } else {
        processedData = response.data || []
      }
    } else {
      // 其他情况，可能直接是购物车列表
      processedData = response || []
    }
    
    // 更新总数
    if (!total.value || total.value === 0) {
      total.value = processedData.length
    }
    
    cartList.value = processedData
    console.log('处理后的购物车数据:', cartList.value)
    
    // 处理SKU规格数据
    cartList.value.forEach(item => {
      if (item.skuDTO && item.skuDTO.specs) {
        item.skuSpecs = item.skuDTO.specs
      }
    })
    
    // 按用户分组购物车数据
    groupCartByUser()
  } catch (error) {
    console.error('获取购物车列表失败:', error)
    ElMessage.error('获取购物车列表失败')
  } finally {
    loading.value = false
  }
}

// 按用户分组购物车数据
const groupCartByUser = () => {
  const userGroups = {}
  
  cartList.value.forEach(item => {
    const userId = item.userId || 'unknown'
    if (!userGroups[userId]) {
      userGroups[userId] = {
        userId: userId,
        userName: item.userName || '未知用户',
        cartItems: []
      }
    }
    userGroups[userId].cartItems.push(item)
  })
  
  // 转换为数组
  userCartGroups.value = Object.values(userGroups)
  
  // 更新总用户数
  total.value = userCartGroups.value.length
  
  console.log('用户购物车分组:', userCartGroups.value)
}

// 获取用户购物车总金额
const getUserCartTotal = (userCart) => {
  return userCart.cartItems.reduce((total, item) => {
    return total + getSubtotal(item)
  }, 0)
}

// 获取总购物车商品数量
const getTotalCartItems = () => {
  return cartList.value.length
}

// 获取商品图片
const getProductImage = (item) => {
  // 检查是否有spuVO和mainImage
  if (item.spuVO && item.spuVO.mainImage) {
    return item.spuVO.mainImage
  }
  // 检查skuDTO中的图片
  if (item.skuDTO && item.skuDTO.mainImage) {
    return item.skuDTO.mainImage
  }
  // 检查直接属性
  if (item.mainImage) {
    return item.mainImage
  }
  if (item.image) {
    return item.image
  }
  // 默认图片
  return '/images/default-product.png'
}

// 获取商品标题
const getProductTitle = (item) => {
  // 检查spuVO中的标题
  if (item.spuVO && item.spuVO.title) {
    return item.spuVO.title
  }
  // 检查直接属性
  if (item.title) {
    return item.title
  }
  if (item.name) {
    return item.name
  }
  // 检查skuDTO中的标题
  if (item.skuDTO && item.skuDTO.title) {
    return item.skuDTO.title
  }
  // 默认值
  return '未知商品'
}

// 获取商品价格
const getProductPrice = (item) => {
  // 优先使用促销价格
  if (typeof item.promotionPrice === 'number') {
    return item.promotionPrice.toFixed(2)
  }
  // 其次使用普通价格
  if (typeof item.price === 'number') {
    return item.price.toFixed(2)
  }
  // 再次检查skuDTO中的价格
  if (item.skuDTO && typeof item.skuDTO.price === 'number') {
    return item.skuDTO.price.toFixed(2)
  }
  // 检查spuVO中的价格
  if (item.spuVO && typeof item.spuVO.price === 'number') {
    return item.spuVO.price.toFixed(2)
  }
  // 默认值
  return '0.00'
}

// 获取商品规格
const getProductSpecs = (item) => {
  try {
    // 检查已处理的规格
    if (item.skuSpecs) {
      return parseSkuSpecs(item.skuSpecs)
    }
    // 检查skuDTO中的规格
    if (item.skuDTO && item.skuDTO.specs) {
      return parseSkuSpecs(item.skuDTO.specs)
    }
    // 检查直接属性
    if (item.specs) {
      return parseSkuSpecs(item.specs)
    }
    return null
  } catch (error) {
    console.error('获取商品规格失败:', error)
    return null
  }
}

// 计算小计金额
const getSubtotal = (item) => {
  try {
    // 获取价格
    let price = 0
    if (typeof item.promotionPrice === 'number') {
      price = item.promotionPrice
    } else if (typeof item.price === 'number') {
      price = item.price
    } else if (item.skuDTO && typeof item.skuDTO.price === 'number') {
      price = item.skuDTO.price
    } else if (item.spuVO && typeof item.spuVO.price === 'number') {
      price = item.spuVO.price
    } else {
      const priceStr = getProductPrice(item)
      price = parseFloat(priceStr) || 0
    }
    
    // 获取数量
    const quantity = parseInt(item.quantity || item.number || 1, 10)
    
    return price * quantity
  } catch (error) {
    console.error('计算小计金额失败:', error)
    return 0
  }
}

// 计算购物车总金额
const getTotalAmount = () => {
  let total = 0
  cartList.value.forEach(item => {
    total += getSubtotal(item)
  })
  return total.toFixed(2)
}

// 解析SKU规格JSON
const parseSkuSpecs = (specs) => {
  if (!specs) return {}
  
  try {
    // 如果已经是对象，直接返回
    if (typeof specs === 'object' && !Array.isArray(specs)) {
      return specs
    }
    
    // 如果是字符串，尝试解析
    if (typeof specs === 'string') {
      // 检查是否是有效的JSON字符串
      if (specs.trim().startsWith('{') && specs.trim().endsWith('}')) {
        return JSON.parse(specs)
      } else {
        // 尝试解析其他格式的字符串
        const specPairs = specs.split(',').map(pair => pair.trim())
        const result = {}
        specPairs.forEach(pair => {
          const [key, value] = pair.split(':').map(item => item.trim())
          if (key && value) {
            result[key] = value
          }
        })
        return result
      }
    }
    
    // 如果是数组，尝试转换为对象
    if (Array.isArray(specs)) {
      const result = {}
      specs.forEach(spec => {
        if (spec.name && spec.value) {
          result[spec.name] = spec.value
        }
      })
      return result
    }
    
    return {}
  } catch (error) {
    console.error('解析SKU规格失败:', error, '原始数据:', specs)
    return {}
  }
}

// 处理分页大小变化
const handleSizeChange = (size) => {
  pageSize.value = size
  fetchCartList()
}

// 处理页码变化
const handleCurrentChange = (page) => {
  currentPage.value = page
  fetchCartList()
}

// 处理搜索
const handleSearch = () => {
  currentPage.value = 1
  fetchCartList()
}

// 刷新数据
const refreshData = () => {
  fetchCartList()
}

// 处理删除购物车项
const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除用户 ${row.userName || row.userId || row.uid || '未知用户'} 的购物车商品 "${getProductTitle(row)}" 吗？`,
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    deleteLoading.value = row.id
    
    try {
      // 使用API服务删除数据
      await deleteCartItem(row.id)
      
      ElMessage.success('删除成功')
      fetchCartList()
    } catch (error) {
      console.error('删除购物车项失败:', error)
      ElMessage.error(`删除失败: ${error.message || '未知错误'}`)
    } finally {
      deleteLoading.value = null
    }
  } catch (error) {
    // 用户取消删除操作
    if (error !== 'cancel') {
      console.error('删除对话框错误:', error)
    }
  }
}

// 清空用户购物车
const handleClearUserCart = async (userId, userName) => {
  if (!userId) {
    ElMessage.warning('用户ID不能为空')
    return
  }
  
  try {
    await ElMessageBox.confirm(
      `确定要清空用户 ${userName || userId} 的所有购物车商品吗？`,
      '警告',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    try {
      // 使用API服务清空用户购物车
      await clearUserCart(userId)
      
      ElMessage.success('清空成功')
      fetchCartList()
    } catch (error) {
      console.error('清空购物车失败:', error)
      ElMessage.error(`清空失败: ${error.message || '未知错误'}`)
    }
  } catch (error) {
    // 用户取消清空操作
    if (error !== 'cancel') {
      console.error('清空对话框错误:', error)
    }
  }
}

// 组件挂载时获取数据
onMounted(() => {
  fetchCartList()
})
</script>

<style lang="scss" scoped>
.cart-list-container {
  padding: 20px;
  width: 100%;
  box-sizing: border-box;

  .page-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;

    h2 {
      margin: 0;
      font-size: 20px;
    }

    .header-actions {
      display: flex;
      gap: 10px;
    }
  }

  .stats-card {
    margin-bottom: 20px;
    width: 100%;
    
    .stats-info {
      display: flex;
      justify-content: space-around;
      
      .stats-item {
        text-align: center;
        
        .stats-label {
          font-size: 14px;
          color: #606266;
        }
        
        .stats-value {
          font-size: 18px;
          font-weight: bold;
          color: #303133;
          margin-left: 5px;
          
          &.price {
            color: #ff4d4f;
          }
        }
      }
    }
  }

  .table-card {
    margin-bottom: 20px;
    width: 100%;
  }

  .cart-table {
    width: 100%;
    table-layout: fixed;
  }

  .cart-items-container {
    padding: 20px;
    background-color: #f9f9f9;
    width: 100%;
    box-sizing: border-box;
  }

  .cart-items-table {
    width: 100%;
    table-layout: fixed;
  }

  .user-info {
    display: flex;
    flex-direction: column;
    gap: 5px;

    div {
      font-size: 14px;
    }
  }

  .product-info {
    display: flex;
    align-items: center;
    gap: 10px;

    .product-image {
      width: 60px;
      height: 60px;
      border-radius: 4px;
      object-fit: cover;
    }
    
    .product-image-small {
      width: 40px;
      height: 40px;
      border-radius: 4px;
      object-fit: cover;
    }

    .product-details {
      display: flex;
      flex-direction: column;
      gap: 5px;

      .product-title {
        font-weight: 500;
      }

      .product-specs {
        display: flex;
        flex-wrap: wrap;
        gap: 5px;

        .spec-tag {
          margin-right: 5px;
        }
      }
      
      .product-shop {
        margin-top: 5px;
      }
    }
  }

  .price {
    color: #ff4d4f;
    font-weight: 500;
  }

  .pagination-container {
    margin-top: 20px;
    display: flex;
    justify-content: flex-end;
  }
  
  .cart-count {
    display: flex;
    align-items: center;
    justify-content: center;
  }
}

/* 修复表格宽度问题 */
:deep(.el-scrollbar__view) {
  width: 100%;
}

:deep(.el-table__inner-wrapper) {
  width: 100%;
}

:deep(.el-card__body) {
  width: 100%;
  padding: 20px;
  box-sizing: border-box;
}
</style> 